import axios from "axios";
import store from "@/store/index.js";
import router from "@/router/index.js";
import { getToken } from "@/util/store.js";
import website from "@/config/website";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { ElMessage } from "element-plus";

axios.defaults.timeout = 10000;
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500;
};
axios.defaults.withCredentials = true;
NProgress.configure({
  showSpinner: false,
});
axios.defaults.baseURL = "/api";
axios.interceptors.request.use(
  (config) => {
    NProgress.start();
    if (getToken()) {
      config.headers[website.Authorization] = getToken();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (res) => {
    NProgress.done();
    const status = res.status || 200;
    const message = res.data.msg || "未知错误";
    if (status === 401) {
      store.dispatch("LogOut").then(() => router.push({ path: "/login" }));
    }
    if (status !== 200 && status !== 401) {
      ElMessage.error(status + "  " + res.statusText);
      return Promise.reject("error");
    }
    if (
      status === 200 &&
      res.data.code !== 200 &&
      res.config.responseType !== "blob"
    ) {
      ElMessage.error(message);
      return Promise.reject("error");
    }
    return res;
  },
  (error) => {
    NProgress.done();
    return Promise.reject(new Error(error));
  }
);

export default axios;
